using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace GraphFS
{
	public class FSEdgeList : Dictionary<Int64, KeyValuePair<Int64,Int64>>
	{



		public void Read(string file)
		{

			FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
			BinaryReader br = new BinaryReader(fs);
			Int64 edgeId = -1;
			Int64 edgeStartNodeId = -1;
			Int64 edgeEndNodeId = -1;
			while (fs.Position < fs.Length)
			{
				edgeId = br.ReadInt64();
				edgeStartNodeId = br.ReadInt64();
				edgeEndNodeId = br.ReadInt64();
				this.Add(edgeId, new KeyValuePair<long,long>(edgeStartNodeId,edgeEndNodeId));
			}
			br.Close();

		}

		public void Write(string file)
		{
			if (File.Exists(file))
			{
				File.Delete(file);
			}

			FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
			BinaryWriter bw = new BinaryWriter(fs);
			foreach (KeyValuePair<Int64, KeyValuePair<Int64, Int64>> kvp in this)
			{
				bw.Write(kvp.Key);
				bw.Write(kvp.Value.Key);
				bw.Write(kvp.Value.Value);
			}
			bw.Flush();
			bw.Close();
		}



		private BinaryReader dataStream = null;

		public FSEdge GetEdge(Int64 edgeId)
		{
			if (!this.ContainsKey(edgeId))
				return null;


			//TODO: check dataStream open

			Int64 startNodeId = this [edgeId].Key;
			Int64 endNodeId = this [edgeId].Value;
			//get nodes from nodelist or something


			/*dataStream.BaseStream.Seek(nodeOffset, SeekOrigin.Begin);
			double lon = dataStream.ReadDouble();
			double lat = dataStream.ReadDouble();

			double nrEdges = dataStream.ReadInt32();
			for (int i = 0; i < nrEdges; i++)
			{
				Int64 edgeId = dataStream.ReadInt64();
			}
			  */
			//TODO: create caching solution for memoization // limit by size, clear by age


			return null;
		}


		public object GetEdge(Int64 startNodeId, Int64 endNodeId)
		{
			
			foreach (KeyValuePair<Int64, KeyValuePair<Int64, Int64>> kvp in this)
			{
				if (kvp.Value.Key == startNodeId && kvp.Value.Value == endNodeId)
				{
					return GetEdge(kvp.Key);
					return null;
				}
			}
			return null;
		}


		public object GetEdges(Int64 includedNodeId)
		{
			List<object> ret;
			foreach (KeyValuePair<Int64, KeyValuePair<Int64, Int64>> kvp in this)
			{
				if (kvp.Value.Key == includedNodeId || kvp.Value.Value == includedNodeId)
				{
					//ret.add(GetEdge(kvp.Key));
					return null;
				}
			}
			return null;


		}

	}
}
